package com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.R;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.LogUtil;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.service.TrailService;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.AppUtils;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.BitmapUtils;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.ChoiceFromAlbum;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.UserLocation;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.callback.LocationCallBack;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.service.UserLocationService;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;


public class HomePHPActivity extends AppCompatActivity{



    private WebView webView;
    private Toolbar tb;

    private Uri imageUri;
    private final int ALBUM_CODE=1;
    private final int CAMERA_CODE=2;
    private Bitmap bitmap;

    private String phone;
    private String photo;
    private Intent serviceIntent;
    private String username;
    private String modular;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_php_home);
        webView= (WebView) findViewById(R.id.mywebview);
        tb= (Toolbar) findViewById(R.id.tb);
        setSupportActionBar(tb);
        Intent intent = getIntent();
        String url = intent.getStringExtra("URL");
        WebSettings settings = webView.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setSupportZoom(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        //打开与JS的交互权限
        settings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        //设置js的回调接口
        webView.addJavascriptInterface(this,"android");
        //webView.loadUrl(ConstantUtils.HOME_PHP_URL);
        webView.loadUrl(url);

        //开启定位服务
        /*serviceIntent = new Intent(this, TrailService.class);
        startService(serviceIntent);*/


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home_menu,menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        /*if(username == null){
            Toast.makeText(this,"请先登录哦",Toast.LENGTH_SHORT).show();
        }*/
        startActivity(new Intent(HomePHPActivity.this,BaibuMapTrackActivity.class));
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStart() {
        super.onStart();
       /* Intent serviceIntent = new Intent(this, TrailService.class);
        startService(serviceIntent);*/

    }


    long firstTime;
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        //KEYCODE_BACK 手机物理回退键　的常量
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
          //设置连续两次点击退出（不超过２秒）
        if(keyCode==KeyEvent.KEYCODE_BACK){
            long secondTime = System.currentTimeMillis();
            if(secondTime-firstTime>2000){
                Toast.makeText(this,"再按一次退出",Toast.LENGTH_SHORT).show();
                firstTime=System.currentTimeMillis();//第一次点击时给firstTime　赋值
                return true;
            }else {
                finish();//关闭Activity
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @JavascriptInterface
    public void GoPayActivity(String price){
        if(price == null){
            Toast.makeText(this,"Parameter Error",Toast.LENGTH_SHORT).show();
            return;
        }

        Log.i("phpback"," price---"+price);
        Intent intent=new Intent(this,CardPayActivity.class);
        intent.putExtra("price",price);
        startActivity(intent);
        //Toast.makeText(this,"暂时不支持",Toast.LENGTH_SHORT).show();

    }
    @JavascriptInterface
    public void goCamera(String phone,String photo,String modular){
        //android.goCamera();
        this.phone=phone;
        this.photo=photo;
        this.modular=modular;
        Log.i("bitmapString","----------js调用拍照");
        //判断版本
        boolean buoldVersion=Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? true:false;
        if(buoldVersion){
            AppUtils.verifyStoragePermissions(this);
            GoCameraSeletedImage();
        }else {
            GoCameraSeletedImage();
        }

    }
    @JavascriptInterface
    public void SendToAndroidUserMesssage(String userPhone){
        //android.SendToAndroidUserMesssage(String userName,String userPhone);
        Log.i("TRAIL","-----userPhone-----"+userPhone);
        boolean userLocationPermission;
        //判断版本
        boolean buoldVersion=Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? true:false;
        if(buoldVersion){
            userLocationPermission = AppUtils.getUserLocationPermission(this);
        }else {
            userLocationPermission=true;
        }

        Log.i("TRAIL","------userLocationPermission-----"+userLocationPermission);

        //开启定位前检查 用户是否同意定位权限，没有同意的话 即使打开也定位不到用户的位置，还浪费资源
        if(!userPhone.isEmpty() && userLocationPermission){
            //开启定位服务
            this.username=userPhone;
            serviceIntent = new Intent(this, TrailService.class);
            serviceIntent.putExtra("Phone",userPhone);
            startService(serviceIntent);
            //开启位置传送服务
            Intent locationIntent=new Intent(this, UserLocationService.class);
            locationIntent.putExtra("username",userPhone);
            startService(locationIntent);
        }
       ;


    }
    @JavascriptInterface
    public void DisplayMap(String[] array){
        LogUtil.i("array","----长度---"+array.length);
        for (int i = 0; i < array.length; i++) {
            LogUtil.i("array","-------"+array[i]);
        }
        Intent intent=new Intent(this,BaibuMapTrackActivity.class);
        intent.putExtra("array",array);
        startActivity(intent);

    }
    @JavascriptInterface
    public  void IntelligenceDoor(){

    }


    public void sendMessageToJS(String message){
        //调用js中的函数：showInfoFromJava(msg)
        webView.loadUrl("javascript:showInfoFromJava('" + message + "')");

    }
    private void GoCameraSeletedImage() {
        File file = new File(this.getExternalCacheDir(), "userInfo_image.jpg");
        try {
            if(file.exists()){
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            Log.e("error",e.getMessage());
        }
        if(Build.VERSION.SDK_INT>=24){//判断版本
            imageUri = FileProvider.getUriForFile(this, "com.getFormPhoto.fileprovider", file);
        }else {
            imageUri= Uri.fromFile(file);
        }
        Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,CAMERA_CODE);
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CAMERA_CODE:
                if(resultCode==RESULT_OK){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            bitmap = ChoiceFromAlbum.getBitmapFromCamera(HomePHPActivity.this, imageUri);
                            if(bitmap ==null){
                                Log.i("bitmapString","-----bitmap == null-----");
                            }
                            File file = BitmapUtils.savaiamge(bitmap,HomePHPActivity.this);
                            pushBitmapToService(file);
                        }
                    }).start();


                }
                break;
        }
    }

    private void pushBitmapToService(File file ){
        if(file == null){
            return;
        }

        HttpParams params = new HttpParams();
        params.put("image",file);
        params.put("phone",phone);
        params.put("photo",photo);
                                //112.74.173.191 业务员APP 照片传输域名
        String url = String.format("http://www.xiaoke111.com/%s/index.php/default/user/get_face", modular);
        LogUtil.i("bitmapString"," url == "+url);
        OkGo.<String>post(url).params(params).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                Log.i("bitmapString","-----照片传输结果-----"+body);
                Toast.makeText(HomePHPActivity.this,body,Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onError(Response<String> response) {
                String body = response.body();
                Log.i("bitmapString","-----照片传输结果错误-----"+body);
            }
        });




    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //stopService(serviceIntent);

    }

    public void testonclick(View view) {
        //startService(serviceIntent);
        //startActivity(new Intent(HomePHPActivity.this,IntelligenceDoorManageActivity.class));
        startActivity(new Intent(HomePHPActivity.this,XunFeiVoiceActivity.class));
        /*Intent intent=new Intent(this,CardPayActivity.class);
        intent.putExtra("price","0.01");
        startActivity(intent);*/


    }



}
